package com.hmall.item.config;


import com.alibaba.fastjson.JSON;
import com.hmall.item.common.BaseContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//自定义拦截器
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入自定义用户请求头拦截器.. 开始编写用户认证逻辑!");
        //获取请求头
        String authorization = request.getHeader("authorization");

        //如果为空说明当前请求没有携带authorization
        if (StringUtils.isBlank(authorization)) {
            System.out.println("-- 用户未登录 --");
            response.setStatus(HttpStatus.SC_FORBIDDEN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write("LOGIN_NOT");
            return false;
        }
        //将请求头中的值转换为Long数值存入ThreadLocal
        Long id = Long.valueOf(authorization);
        BaseContext.setCurrentId(id);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("目标资源方法执行后执行 postHandle ... ");
        System.err.println("ID{" + BaseContext.getCurrentId() + "}用户: 目标方法执行完毕!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("视图渲染完毕后执行，最后执行 afterCompletion .... ");

    }
}
